package com.dede.monochromatism.service

import android.accessibilityservice.AccessibilityService
import android.content.Intent
import android.view.accessibility.AccessibilityEvent
import com.dede.applib.extends.getBoolean
import com.dede.applib.extends.getInt
import com.dede.applib.util.LogExtends
import com.dede.applib.util.i
import com.dede.monochromatism.*
import com.dede.monochromatism.db.PackageDb
import com.dede.monochromatism.db.contains
import com.dede.monochromatism.util.Util
import java.util.*

/**
 * @author hsh
 * @time 2017/7/17 017 上午 10:28.
 * @doc 通过无障碍服务监听所有App的窗口状态改变
 */
class PackageChangeListenerServer : AccessibilityService(), LogExtends {

    override fun onInterrupt() {
        i("onInterrupt: 服务将要被关闭")
    }

    private var lastPackageName = ""

    companion object {
        private var sPackageName = ""
        fun getPackageName() = sPackageName
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        val packageName = event.packageName.toString()
        i("onAccessibilityEvent：$packageName")
        if (lastPackageName != packageName) {
            i("packageChange=====>>>>>>$packageName")
            packageChange(packageName)//包名改变
        }
        lastPackageName = packageName
    }

    private fun packageChange(packageName: String) {
        sPackageName = packageName

        if (!PackageDb.getIgnoreList().contains(packageName)) {
            val context = applicationContext
            val state = context.getBoolean(S_PRE_TIME, false)
            if (state) {//多应用支持
                val shouldOpen = PackageDb.getOpenList().contains(packageName)

                val thisCalendar = Calendar.getInstance()
                if (shouldOpen) {
                    val openCalendar = TimeJobService.createCalendar(context.getInt(openHour),
                            context.getInt(openMinute))
                    if (!thisCalendar.before(openCalendar)) {
                        Util.setSimulateColorSpaceState(context, true)
                    }
                } else {
                    val closeCalendar = TimeJobService.createCalendar(context.getInt(closeHour),
                            context.getInt(closeMinute))
                    if (!thisCalendar.before(closeCalendar)) {
                        Util.setSimulateColorSpaceState(context, false)
                    }
                }
            } else {//所用应用支持
                Util.setSimulateColorSpaceState(context, PackageDb.getOpenList().contains(packageName))
            }
        }
    }

    override fun onServiceConnected() {
        super.onServiceConnected()
        i("onServiceConnected: 服务连接")
    }

    override fun onUnbind(intent: Intent): Boolean {
        i("onUnbind: 关闭服务")
        return super.onUnbind(intent)
    }

}